package cn.com.heaton.bleLib.logic;

import android.util.Log;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

public class HttpURLConnHelper {

    public static String TAG = "HttpURLConnHelper";

    public static final String AppId = "20171124000000";
    public static final String AppPwd = "525ECF00CD764192A914628FD933DAC6";

    /**
     * 直接传入16bit的数据
     *
     * @param macRandom
     * @return
     */
    public static byte[] loadByteFromLocal(byte[] macRandom) {
//        BleLog.i(TAG, "收到的加密数据" + HexUtil.encodeHexStr(macRandom));
        //收到的加密数据分高低8字节两部分进行3DES解密，
        byte[] litterByte = new byte[8];
        byte[] higherByte222 = new byte[8];
//        for (int i = 0; i < 8; i++) {
//            litterByte[i] = macRandom[i];
//            higherByte[i] = macRandom[i + 8];
//        }
        litterByte[0] = macRandom[0];
        litterByte[1] = macRandom[1];
        litterByte[2] = macRandom[2];
        litterByte[3] = macRandom[3];
        litterByte[4] = macRandom[4];
        litterByte[5] = macRandom[5];
        litterByte[6] = macRandom[6];
        litterByte[7] = macRandom[7];

        higherByte222[0] = macRandom[8];
        higherByte222[1] = macRandom[9];
        higherByte222[2] = macRandom[10];
        higherByte222[3] = macRandom[11];
        higherByte222[4] = macRandom[12];
        higherByte222[5] = macRandom[13];
        higherByte222[6] = macRandom[14];
        higherByte222[7] = macRandom[15];

        System.out.print("litter:---->" + HexUtil.encodeHexStr(litterByte) + "\n");
        System.out.print("higher:---->" + HexUtil.encodeHexStr(higherByte222) + "\n");

        //得到两部分解密后的数据
        byte[] litDecByte = DES3Utils.decryptMode(litterByte);
        byte[] higDescByte = DES3Utils.decryptMode(higherByte222);
        System.out.print("litter dec:---->" + HexUtil.encodeHexStr(litDecByte) + "\n");
        System.out.print("higher dec:---->" + HexUtil.encodeHexStr(higDescByte) + "\n");
        //将得到的两个数据组合成一个数组，得到解密后的数据
        //将解密数据进行换算，得到原始数据
        byte[] highByte = new byte[8];
//        highByte[0] = (byte) (litDecByte[7] ^ higDescByte[7]);
//        highByte[1] = (byte) (litDecByte[6] ^ higDescByte[6]);
//        highByte[2] = (byte) (litDecByte[5] ^ higDescByte[5]);
//        highByte[3] = (byte) (litDecByte[4] ^ higDescByte[4]);
//        highByte[4] = (byte) (litDecByte[3] ^ higDescByte[3]);
//        highByte[5] = (byte) (litDecByte[2] ^ higDescByte[2]);
//        highByte[6] = (byte) (litDecByte[1] ^ higDescByte[1]);
//        highByte[7] = (byte) (litDecByte[0] ^ higDescByte[0]);
        highByte[0] = (byte) (litDecByte[0] ^ higDescByte[0]);
        highByte[1] = (byte) (litDecByte[1] ^ higDescByte[1]);
        highByte[2] = (byte) (litDecByte[2] ^ higDescByte[2]);
        highByte[3] = (byte) (litDecByte[3] ^ higDescByte[3]);
        highByte[4] = (byte) (litDecByte[4] ^ higDescByte[4]);
        highByte[5] = (byte) (litDecByte[5] ^ higDescByte[5]);
        highByte[6] = (byte) (litDecByte[6] ^ higDescByte[6]);
        highByte[7] = (byte) (litDecByte[7] ^ higDescByte[7]);

        System.out.print("Mac+Random original:---->" + HexUtil.encodeHexStr(highByte) + "\n");
        //得到原始数据
        byte[] realByte = new byte[16];
        System.arraycopy(highByte, 0, realByte, 0, highByte.length);
        System.arraycopy(higDescByte, 0, realByte, highByte.length, higDescByte.length);
        System.out.print("原始数据---->" + HexUtil.encodeHexStr(realByte) + "\n");
        //进行数据加密
        byte R2Byte = realByte[10];
        byte R5Byte = realByte[13];
        //Mac跟随机码异或，再跟随机码组成新的8个字节
        byte[] resultByte = new byte[8];
        resultByte[7] = R5Byte;
        resultByte[6] = R2Byte;
        //new byte
        resultByte[0] = (byte) (realByte[0] ^ R2Byte);
        resultByte[1] = (byte) (realByte[1] ^ R5Byte);
        resultByte[2] = (byte) (realByte[2] ^ R2Byte);
        resultByte[3] = (byte) (realByte[3] ^ R5Byte);
        resultByte[4] = (byte) (realByte[4] ^ R2Byte);
        resultByte[5] = (byte) (realByte[5] ^ R5Byte);
        System.out.print("返回未加密数据---->" + HexUtil.encodeHexStr(resultByte) + "\n");
//        BleLog.i(TAG, "原始数据：" + HexUtil.encodeHexStr(resultByte));
        byte[] resultEncyByte = DES3Utils.encryptMode(resultByte);
        System.out.print("返回加密数据---->" + HexUtil.encodeHexStr(resultEncyByte) + "\n");
        return resultEncyByte;


    }

    /**
     * 生成密钥开门
     *
     * @param macRandom
     * @return
     */
    public static byte[] loadByteFromURL(String macRandom) {
        macRandom = macRandom.replace("/", "_").replace("+", "-").replace("=", "%3D").replaceAll("[\\s*\t\n\r]", "");

        String encoding = "utf-8";
        HttpURLConnection httpConn = null;
        BufferedInputStream bis = null;
        String url = "http://120.26.198.83:18587/api/key/generate/1?macRandom=" + macRandom;
        try {
            URL urlObj = new URL(url);
            httpConn = (HttpURLConnection) urlObj.openConnection();
            //添加Header
            httpConn.setRequestProperty("AppId", AppId);
            String seed = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            httpConn.setRequestProperty("Seed", seed);
            int sign = 0;
            StringBuilder sbSign = new StringBuilder(AppId).append(AppPwd).append(seed);
            for (byte b : sbSign.toString().getBytes()) {
                sign += b;
            }
            httpConn.setRequestProperty("Sign", String.valueOf(sign));
            httpConn.setRequestMethod("GET");
            httpConn.setDoInput(true);
            httpConn.setRequestProperty("Charset", encoding);
            httpConn.setConnectTimeout(5000);
            httpConn.connect();
            Log.e(TAG, "httpUrlConnecttion responseCode : " + httpConn.getResponseCode());
            if (httpConn.getResponseCode() == 200) {
                bis = new BufferedInputStream(httpConn.getInputStream());
                return streamToByte(bis);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bis != null) {
                    bis.close();
                }
                httpConn.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 生成二维码名片
     *
     * @param time 开门时间，格式  yyyyMMddHHmm
     * @param c    社区号
     * @param d    设备号
     * @return
     */
    public static byte[] generateQrCode(String time, String c, String d) {
        String encoding = "utf-8";
        HttpURLConnection httpConn = null;
        BufferedInputStream bis = null;
        String url = "http://120.26.198.83:18587/api/token/qrcode/1?t=" + time + "&c=" + c + "&d=" + d + "&w=300";
        try {
            URL urlObj = new URL(url);
            httpConn = (HttpURLConnection) urlObj.openConnection();
            //添加Header
            httpConn.setRequestProperty("AppId", AppId);
            String seed = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            httpConn.setRequestProperty("Seed", seed);
            int sign = 0;
            StringBuilder sbSign = new StringBuilder(AppId).append(AppPwd).append(seed);
            for (byte b : sbSign.toString().getBytes()) {
                sign += b;
            }
            httpConn.setRequestProperty("Sign", String.valueOf(sign));
            httpConn.setRequestMethod("GET");
            httpConn.setDoInput(true);
            httpConn.setRequestProperty("Charset", encoding);
            httpConn.setConnectTimeout(5000);
            httpConn.connect();
            Log.e(TAG, "httpUrlConnecttion responseCode : " + httpConn.getResponseCode());
            if (httpConn.getResponseCode() == 200) {
                bis = new BufferedInputStream(httpConn.getInputStream());
                return streamToByte(bis);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bis != null) {
                    bis.close();
                }
                httpConn.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static byte[] streamToByte(InputStream is) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int c = 0;
        byte[] buffer = new byte[8 * 1024];
        try {
            while ((c = is.read(buffer)) != -1) {
                baos.write(buffer, 0, c);
                baos.flush();
            }
            return baos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    private static HashMap<String, String> dictionary = new HashMap<String, String>() {
        {
            put("a", "g");
            put("b", "u");
            put("c", "6");
            put("d", "t");
            put("e", "h");
            put("f", "9");
            put("g", "x");
            put("h", "0");
            put("i", "b");
            put("j", "f");
            put("k", "5");
            put("l", "e");
            put("m", "1");
            put("n", "a");
            put("o", "d");
            put("p", "i");
            put("q", "3");
            put("r", "c");
            put("s", "z");
            put("t", "2");
            put("u", "p");
            put("v", "7");
            put("w", "n");
            put("x", "4");
            put("y", "s");
            put("z", "8");

            put("0", "l");
            put("1", "r");
            put("2", "o");
            put("3", "m");
            put("4", "y");
            put("5", "k");
            put("6", "w");
            put("7", "q");
            put("8", "j");
            put("9", "v");
        }
    };


    /**
     * 生成二维码图片数据
     *
     * @param time 开门时间，格式  yyyyMMddHHmm
     * @param c    社区号
     * @param d    设备号
     * @return
     */
    public static String generateQrCodeString(String time, String c, String d) {
        String s = String.format("lqr_1_%s_%s_%s", c, d, dateToStamp(time));
        System.out.print(s);
        StringBuilder sb = new StringBuilder();
        for (char cha : s.toCharArray()) {
            if (dictionary.containsKey(String.valueOf(cha))) {
                sb.append(dictionary.get(String.valueOf(cha)));
            } else {
                sb.append(cha);
            }
        }
        return sb.toString();
    }


    /*
     * 将时间转换为时间戳
     */
    public static String dateToStamp(String s) {
        String res = "";
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmm");
            Date date = simpleDateFormat.parse(s);
            long ts = date.getTime();
            res = String.valueOf(ts);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return res;
    }


}
